import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";
import { log } from "console";

// 创建 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_URL, // 从环境变量获取基础URL
  timeout: 15000, // 请求超时时间
  headers: {
    "Content-Type": "application/json;charset=utf-8"
  }
});

// 请求拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // const userStore = useUserStore();
    const userInfo = JSON.parse(localStorage.getItem("user-info")) || "{}";
    // 如果有token，添加到请求头
    // console.log("userInfo:", userInfo);
    if (userInfo.refreshToken) {
      config.headers = {
        ...config.headers,
        token: `${userInfo.refreshToken}`
      };
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, message, data } = response.data;

    // 根据自定义错误码判断请求是否成功
    if (code === 200) {
      // 成功返回数据
      return Promise.resolve(response.data);
    } else {
      // 处理业务错误
      ElMessage.error(message || "操作失败");
      return Promise.reject(new Error(message || "Error"));
    }
  },
  error => {
    // 处理 HTTP 网络错误
    let message = "";
    // HTTP 状态码判断
    switch (error.response?.status) {
      case 401:
        message = "登录已过期，请重新登录";
        // 清除用户信息，跳转登录页
        const userStore = useUserStore();
        userStore.logout();
        break;
      case 403:
        message = "无权限访问";
        break;
      case 404:
        message = "请求地址错误";
        break;
      case 500:
        message = "服务器故障";
        break;
      default:
        message = "网络连接故障";
    }

    ElMessage.error(message);
    return Promise.reject(error);
  }
);

export default service;
